package yunwo.cn.yzstation.printer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;



import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import yunwo.cn.yzstation.R;

/**
 * 根类Activity
 * 
 */
public abstract class PriftBaseActivity extends FragmentActivity {
	/** 记录处于前台的Activity */
	private static PriftBaseActivity mForegroundActivity = null;
	/** 记录所有活动的Activity */
	private static final List<PriftBaseActivity> mActivities = new LinkedList<PriftBaseActivity>();
	private static final String TAG = "BaseActivity";
	public static final String SHAREPREFERENCE_NAME = "cwlptShareperference";
	private View headview;
	protected TextView btn_right;
	private RelativeLayout btn_right_rl;
//	public static ACache mCache;
	public static SharedPreferences sharedPreferences;
	public static SharedPreferences infoPreferences;
//	public static ACache sendGoodsCache;

	String tag = getClass().getSimpleName();
	private BluetoothSocket mSocket;
	private BluetoothStateReceiver mBluetoothStateReceiver;
	private AsyncTask mConnectTask;
	private ProgressDialog mProgressDialog;

	/**
	 * 蓝牙连接成功后回调，该方法在子线程执行，可执行耗时操作
	 */
	public abstract void onConnected(BluetoothSocket socket, int taskType);


	/**
	 * 蓝牙状态发生变化时回调
	 */
	public void onBluetoothStateChanged(Intent intent) {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		setBaiduInfo();
		super.onCreate(savedInstanceState);
	/*	mCache = ACache.get(this);
		sendGoodsCache = ACache.get(this);*/
		mActivities.add(this);
		sharedPreferences = getSharedPreferences(SHAREPREFERENCE_NAME,
				Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
		initReceiver();
	}

	@Override
	protected void onStop() {
		cancelConnectTask();
		closeSocket();
		super.onStop();
	}
	protected void closeSocket() {
		if (mSocket != null) {
			try {
				mSocket.close();
			} catch (IOException e) {
				mSocket = null;
				e.printStackTrace();
			}
		}
	}

	protected void cancelConnectTask() {
		if (mConnectTask != null) {
			mConnectTask.cancel(true);
			mConnectTask = null;
		}
	}


	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		headview = this.findViewById(R.id.title_bar);
	}

	/**
	 *
	 * @param leftImg
	 *            0表示图标为 R.drawable.header_icon_back
	 * @param leftClick
	 * @param title
	 * @param rightClick
	 * @return
	 */
/*
	protected PriftBaseActivity setTitleBar(int leftImg,
											View.OnClickListener leftClick, String title, String rightStr,
											View.OnClickListener rightClick) {
		if (leftImg == 0) {
			this.setLeftButton(R.drawable.header_return, leftClick)
					.setTitleBar(title).setRightButton(rightStr, rightClick)
					.showTitleBar();
		} else {
			this.setLeftButton(leftImg, leftClick).setTitleBar(title)
					.setRightButton(rightStr, rightClick).showTitleBar();
		}
		return this;
	}
*/

	/**
	 * 设置标题
	 * 
	 * @param title
	 * @return
	 */
	protected PriftBaseActivity setTitleBar(String title) {
		TextView tv_title = (TextView) headview.findViewById(R.id.title);
		tv_title.setText(Html.fromHtml(title));
		tv_title.setVisibility(View.VISIBLE);
		return this;
	}

	/**
	 * 显示头部左边的图标
	 * 
	 * @param imgRid
	 * @param onClick
	 * @return
	 */
/*
	protected PriftBaseActivity setLeftButton(int imgRid,
											  View.OnClickListener onClick) {
		ImageView leftLL = (ImageView) headview.findViewById(R.id.leftLL);
		leftLL.setOnClickListener(onClick);
		leftLL.setVisibility(View.VISIBLE);
		leftLL.setImageResource(imgRid);
		return this;
	}
*/

	/**
	 * 显示头部右边的图标
	 * 
	 * @param onClick
	 * @return
	 */
/*
	protected PriftBaseActivity setRightButton(String rightStr,
											   View.OnClickListener onClick) {
		btn_right = (TextView) headview.findViewById(R.id.rightTV);
		btn_right.setOnClickListener(onClick);
		btn_right.setText(rightStr);
		if (!StringUtil.isEmpty(rightStr)) {
			btn_right.setVisibility(View.VISIBLE);
			btn_right.setOnClickListener(onClick);
		}
		return this;
	}
*/

	/**
	 * 显示头部
	 * 
	 * @return
	 */
	protected PriftBaseActivity showTitleBar() {
		headview.setVisibility(View.VISIBLE);
		return this;
	}

	/**
	 * 隐藏头部
	 * 
	 * @return
	 */
	protected PriftBaseActivity hideTitleBar() {
		headview.setVisibility(View.GONE);
		return this;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBluetoothStateReceiver);
		 mActivities.remove(this);

	}

	private void initReceiver() {
		mBluetoothStateReceiver = new BluetoothStateReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		registerReceiver(mBluetoothStateReceiver, filter);
	}

/*	public boolean checkBluetoothState() {
		if (BluetoothUtil.isBluetoothOn()) {
			return true;
		} else {
			BluetoothUtil.openBluetooth(this);
			return false;
		}
	}*/

/*
	public void connectDevice(BluetoothDevice device, int taskType) {
		if (checkBluetoothState() && device != null) {
			mConnectTask = new ConnectBluetoothTask(taskType).execute(device);
		}
	}
*/


	class ConnectBluetoothTask extends AsyncTask<BluetoothDevice, Integer, BluetoothSocket> {

		int mTaskType;

		public ConnectBluetoothTask(int taskType) {
			this.mTaskType = taskType;
		}

		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍候...");
			super.onPreExecute();
		}

		@Override
		protected BluetoothSocket doInBackground(BluetoothDevice... params) {
			if(mSocket != null){
				try {
					mSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
//			mSocket = BluetoothUtil.connectDevice(params[0]);;
			onConnected(mSocket, mTaskType);
			return mSocket;
		}

		@Override
		protected void onPostExecute(BluetoothSocket socket) {
			mProgressDialog.dismiss();
			if (socket == null || !socket.isConnected()) {
				toast("连接打印机失败");
			} else {
				toast("成功！");
			}

			super.onPostExecute(socket);
		}
	}



	protected void showProgressDialog(String message) {
		if (mProgressDialog == null) {
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setCancelable(false);
		}
		mProgressDialog.setMessage(message);
		if (!mProgressDialog.isShowing()) {
			mProgressDialog.show();
		}
	}

	protected void toast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}


	class BluetoothStateReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
			switch (state) {
				case BluetoothAdapter.STATE_TURNING_ON:
					toast("蓝牙已开启");
					break;

				case BluetoothAdapter.STATE_TURNING_OFF:
					toast("蓝牙已关闭");
					break;
			}
			onBluetoothStateChanged(intent);
		}
	}


	@Override
	protected void onResume() {
		mForegroundActivity = this;
//		LogUtil.d(TAG, "mForegroundActivity:" + mForegroundActivity);
		super.onResume();
//		MobclickAgent.onResume(this);
//		MobclickAgent.onPageStart(getClass().toString());
	}

	@Override
	protected void onPause() {
		mForegroundActivity = null;
		super.onPause();
//		MobclickAgent.onPause(this);
//		MobclickAgent.onPageEnd(getClass().toString());
	}


	/** 是否有启动的Activity */
	public static boolean hasActivity() {
		return mActivities.size() > 0;
	}

	/** 获取当前处于前台的activity */
	public static PriftBaseActivity getForegroundActivity() {
		return mForegroundActivity;
	}

	public static int getActivitySize() {
		return mActivities.size();
	}

	/** 获取当前处于栈顶的activity，无论其是否处于前台 */
	public static PriftBaseActivity getCurrentActivity() {
		List<PriftBaseActivity> copy;
		synchronized (mActivities) {
			copy = new ArrayList<PriftBaseActivity>(mActivities);
		}
		if (copy.size() > 0) {
			return copy.get(copy.size() - 1);
		}
		return null;
	}

	/**
	 * 判断是否存在指定类的activity
	 * 
	 * @param clazz
	 * @return
	 */
	public static boolean hasActivity(Class clazz) {
		List<PriftBaseActivity> copy;
		synchronized (mActivities) {
			copy = new ArrayList<PriftBaseActivity>(mActivities);
		}
		for (PriftBaseActivity activity : copy) {
			if (activity.getClass().getName().equals(clazz.getName())) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 判断是否存在指定类的activity
	 *
	 * @param activity
	 * @return
	 */
	public static boolean hasActivity(Activity activity) {
		if(activity!=null){
			return mActivities.contains(activity);
		}
		return false;
	}

	/**
	 * 关闭指定类的activity
	 * 
	 * @param clazz
	 */
	public static void finishActivity(Class clazz) {
		List<PriftBaseActivity> copy;
		synchronized (mActivities) {
			copy = new ArrayList<PriftBaseActivity>(mActivities);
		}
		for (PriftBaseActivity activity : copy) {
			if (activity != null
					&& activity.getClass().getName().equals(clazz.getName())) {
				activity.finish();
			}
		}
	}




}
